﻿//-----------------------------------------------------------------------
// <copyright file="ProcessExtensions.cs" company="CodePlex">
//     Copyright (c) Doug Holland, CodePlex. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------
namespace CodePlex.Diagnostics
{
    using System;

    using System.Diagnostics;

    using System.Globalization;

    /// <summary>
    /// Provides an extension method for the <see cref="T:System.Diagnostics.Process"/> class to enable process exit details to be updated within the CodePlex.Diagnostics database.
    /// </summary>
    public static class ProcessExtensions
    {
        #region public static void UpdateExitDetails(this Process process)

        /// <summary>
        /// Updates details about how and when the <see cref="T:System.Diagnostics.Process"/> exited within the CodePlex.Diagnostics database.
        /// </summary>
        /// <param name="process">The <see cref="T:System.Diagnostics.Process"/> for which details about how and when it exited should be published.</param>
        /// <remarks>
        /// Process exit details are only published if exceptions were published or log entries were written while the process was alive. 
        /// </remarks>
        public static void UpdateExitDetails(this Process process)
        {
            if (process.HasExited)
            {
                // establish a proxy to the diagnostics service.
                DiagnosticsServiceClient client = null;

                try
                {
                    // establish a proxy to the diagnostics service.
                    client = new DiagnosticsServiceClient();

                    // update the process exited details within the CodePlex.Diagnostics database. 
                    IAsyncResult result = client.BeginUpdateProcessExitInformation(process.Id, process.StartTime, process.ExitTime, process.ExitCode, null, null);

                    // complete the update of process exited information.
                    client.EndUpdateProcessExitInformation(result);

                    // causes the client to transition from its current state into the closed state.
                    client.Close();
                }
                catch
                {
                    // causes the client to transition immediately from its current state into the closed state.
                    if (client != null)
                    {
                        client.Abort();
                    }
                }
            }
            else
            {
                // unable to update process exited detils for a process that is stil alive.
                throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, SR.GetString(SR.ProcessAlive), process.Id));
            }
        }

        #endregion
    }
}
